package com.gict.antifraudback.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gict.antifraudback.entity.Article;
import com.gict.antifraudback.entity.ArticleTags;
import com.gict.antifraudback.entity.Tags;
import com.gict.antifraudback.service.ArticleTagsService;
import com.gict.antifraudback.service.TagsService;
import com.gict.antifraudback.mapper.TagsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author xie
* @description 针对表【tags】的数据库操作Service实现
* @createDate 2023-11-01 23:46:05
*/
@Service
public class TagsServiceImpl extends ServiceImpl<TagsMapper, Tags>
    implements TagsService{

    @Autowired
    private ArticleTagsService articleTagsService;

    @Override
    public void setTagsName(List<Article> recommendArticleList) {
        if (!recommendArticleList.isEmpty()){
            List<Integer> ids = recommendArticleList.stream().map(Article::getId).collect(Collectors.toList());
            List<ArticleTags> articleTagsList = articleTagsService.listByArticleIds(ids);
            if (!articleTagsList.isEmpty()){
                // articleId => tags
                Map<Integer, List<Integer>> tagsMap = articleTagsList.stream().collect(Collectors.groupingBy(ArticleTags::getArticleId, Collectors.mapping(ArticleTags::getTagId, Collectors.toList())));
                Set<Integer> set = new HashSet<>();
                for (List<Integer> value : tagsMap.values()) {
                    set.addAll(value);
                }
                Collection<Tags> tags = listByIds(new ArrayList<>(set));
                if (CollectionUtils.isNotEmpty(tags)){
                    Map<Integer, String> map = tags.stream().collect(Collectors.toMap(Tags::getId, Tags::getName));
                    for (Article article : recommendArticleList) {
                        List<Integer> tagsIds = tagsMap.get(article.getId());
                        List<String> tagsName = new ArrayList<>();
                        if (CollectionUtils.isNotEmpty(tagsIds)){
                            for (Integer tagsId : tagsIds) {
                                String name = map.get(tagsId);
                                if (name != null){
                                    tagsName.add(name);
                                }
                            }
                        }

                        article.setTagsName(tagsName);
                    }
                }
            }
        }
    }

}




